#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   dbhelp.py
@Time    :   2023/05/05 14:57:34
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from pydantic import parse_obj_as
from tortoise.exceptions import OperationalError

from ..models import PostModel as Post,TagModel,PostTagsModel,CommentModel


async def get_last_post():
    post_obj = await Post.filter(is_published=True, status=1).order_by('-modified').first()
    return post_obj


async def get_post(pid):
    post_obj = await Post.get_or_none(pk=pid, status=1)
    if post_obj is None:
        return None
    return post_obj


async def get_all_post(offset=0, limit=10):
    posts_query = Post.filter(is_published=True, status=1).offset(offset).limit(limit)
    posts = await posts_query.all()
    posts_list = []
    for post_obj in posts:
        tag_list = await get_post_tags(post_obj)
        post_obj.tags = tag_list
        posts_list.append(post_obj)
    return posts_list 


async def get_post_tags(post_obj):
    result = await PostTagsModel.filter(post=post_obj, status__not=9).all()
    tag_list = []
    for post_tag in result:
        tag_obj = await post_tag.tag.filter(status__not=9).all()
        tag_list.append(tag_obj.name)
    return tag_list


async def get_tag(tid):
    tag = await TagModel.get_or_none(pk=tid, status=1)
    if tag is None:
        return None
    return tag


async def get_all_tags(offset=0, limit=10):
    tags_query = TagModel.filter(status=1).offset(offset).limit(limit)
    tags_list = await tags_query.all()
    return tags_list 


async def get_tag_posts(tag_obj, offset=0, limit=10):
    result = await PostTagsModel.filter(tag=tag_obj, status__not=9).offset(offset).limit(limit)
    # result = await result_query.all()
    posts_list = []
    for post_tag in result:
        post_obj = await post_tag.post.filter(status__not=9).all()
        posts_list.append(post_obj)
    return posts_list


async def get_comment_by_id(cid):
    comment = await CommentModel.get_or_none(pk=cid, status=1)
    if comment is None:
        return None
    return comment


async def get_comments_by_post(pid,offset=0, limit=10):
    comments_query = await CommentModel.filter(post_id=pid, status__not=9).offset(offset).limit(limit)
    comments_list = await comments_query.all()
    return comments_list

